﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Model;
using VAdvantage.Grids;
using VAdvantage.Panels;
using VAdvantage.Classes;
using VAdvantage.Logging;
using VAdvantage.Controls;
using VAdvantage.Utility;
using System.ComponentModel;
using System.Collections;
using System.Text;
using System.Data;
using VAdvantage.DataBase;
using System.Threading;
using System.Windows.Data;

namespace VAdvantage.Dialogs
{

   

    public partial class VAccountDialog : ChildWindow,IBusy
    {

        #region "Declaration"

        /** Window No					*/
        private int _windowNo;
        /**	Journal Entry				*
        private boolean				m_onlyNonDocControlled = false;
        /** Selection changed			*/
        protected bool _changed = false;

        /** Accounting Schema           */
        private static MAcctSchema _AcctSchema = null;
        /** MWindow for AccountCombination  */
        private GridWindow _mWindow = null;
        /** MTab for AccountCombination     */
        private GridTab _mTab = null;
        /** GridController                  */
        private GridController _gridController = null;

        /** Account used                */
        private MAccountLookup _mAccount = null;
        /** Result                      */
        private int _C_ValidCombination_ID;
        /** Acct Schema					*/
        private int _C_AcctSchema_ID = 0;
        /** Client                      */
        private int _AD_Client_ID;
        /** Where clause for combination search */
        private Query _query;
        /**	Logger			*/
        private static VLogger log = VLogger.GetVLogger(typeof(VAccountDialog).FullName);

        /** row count */
        int rowCount = -1;

        //  Editors for Query
        private IControl f_Alias, f_Combination,
            f_AD_Org_ID, f_Account_ID, f_SubAcct_ID,
            f_M_Product_ID, f_C_BPartner_ID, f_C_Campaign_ID, f_C_LocFrom_ID, f_C_LocTo_ID,
            f_C_Project_ID, f_C_SalesRegion_ID, f_AD_OrgTrx_ID, f_C_Activity_ID,
            f_User1_ID, f_User2_ID;
        //
        private VLabel f_Description = new VLabel();

        private bool _newRow = true;

        private BindingSource _bs = null;

        private DataUtil.DataObject currentRow = null;

        #endregion


        public VAccountDialog()
        {
            InitializeComponent();
            LayoutRoot.Background = new SolidColorBrush(GlobalVariable.WINDOW_BACK_COLOR);
        }

        /// <summary>
        ///	Constructor
        /// </summary>
        /// <param name="frame"></param>
        /// <param name="title"></param>
        /// <param name="mAccount"></param>
        /// <param name="C_AcctSchema_ID"></param>
        public VAccountDialog(String title,
            MAccountLookup mAccount, int C_AcctSchema_ID)
            : this()
        {
            //this.SetTitle(title);
            Title = title;
            log.Config("C_AcctSchema_ID=" + C_AcctSchema_ID
                + ", C_ValidCombination_ID=" + mAccount.C_ValidCombination_ID);
            _mAccount = mAccount;
            _C_AcctSchema_ID = C_AcctSchema_ID;
            _windowNo = Envs.CreateWindowNo(this);
            try
            {
                InitializeComponent();
                LayoutRoot.Background = new SolidColorBrush(GlobalVariable.WINDOW_BACK_COLOR);
                JbInit();
            }
            catch (Exception ex)
            {
                log.Log(Level.SEVERE, ex.ToString());
            }
            //if (InitAccount())
            //    this.Show();
            //else
            //    this.Close();
            //dispose();
            InitAccount();
            this.Show();
            SetBusy(true);
        }

        public void SetBusy(bool isbusy)
        {
            this.Cursor = isbusy ? Cursors.Wait : Cursors.Arrow;
            
            this.IsEnabled = !isbusy;

            if (isbusy)
            {
                rowCount = -1;
            }

            //if (!isbusy && rowCount>0)
            //{
            //    statusBar.SetStatusDB(rowCount.ToString());
            //}
        }

        private void JbInit()
        {
            //btnSave.ToolTipText = Msg.GetMsg(Envs.GetContext(), "AccountNewUpdate");
            //btnRefresh.ToolTipText = Msg.GetMsg(Envs.GetContext(), "Refresh");
            //btnIgnore.ToolTipText = Msg.GetMsg(Envs.GetContext(), "Ignore");
            gpTitle.Header = Msg.GetMsg(Envs.GetCtx(), "Parameter");
        }

        /**
	 *	Dyanmic Init.
	 *  When a row is selected, the editor values are set
	 *  (editors do not change grid)
	 *  @return true if initialized
	 */
        private bool InitAccount()
        {

            BackgroundWorker bgw = new BackgroundWorker();
            MAcctSchemaElement[] elements = null;
            bgw.DoWork += (sd,ed) =>
                {
                    ed.Result = true;

                    _AD_Client_ID = Envs.GetCtx().GetContextAsInt(_windowNo, "AD_Client_ID");
                    if (_AcctSchema == null || _AcctSchema.GetC_AcctSchema_ID() != _C_AcctSchema_ID)
                        _AcctSchema = new MAcctSchema(Envs.GetCtx(), _C_AcctSchema_ID, null);
                    log.Config(_AcctSchema.ToString()
                        + ", #" + _AcctSchema.GetAcctSchemaElements().Length);
                    Envs.GetCtx().SetContext(_windowNo, "C_AcctSchema_ID", _C_AcctSchema_ID);

                    elements = _AcctSchema.GetAcctSchemaElements();


                    //  Model
                    int AD_Window_ID = 153;		//	Maintain Account Combinations 
                    GridWindowVO wVO = AEnv.GetMWindowVO(_windowNo, AD_Window_ID, 0);

                    if (wVO == null)
                    {
                        ed.Result = false;
                        return;
                    }
                    _mWindow = new GridWindow(wVO);
                    _mTab = _mWindow.GetTab(0);
                    //  ParameterPanel restrictions
                    _mTab.GetField("Alias").SetDisplayLength(15);
                    _mTab.GetField("Combination").SetDisplayLength(15);
                    //  Grid restrictions
                    _mTab.GetField("AD_Client_ID").SetDisplayed(false);
                    _mTab.GetField("C_AcctSchema_ID").SetDisplayed(false);
                    _mTab.GetField("IsActive").SetDisplayed(false);
                    _mTab.GetField("IsFullyQualified").SetDisplayed(false);
                    //  don't show fields not being displayed in this environment
                    for (int i = 0; i < _mTab.GetFieldCount(); i++)
                    {
                        GridField field = _mTab.GetField(i);
                        if (!field.IsDisplayed(true))      //  check context
                            field.SetDisplayed(false);
                    }
                };

            bgw.RunWorkerCompleted += (sc, ec) =>
                {
                    if (!(bool)ec.Result)
                    {
                        this.DialogResult = false;
                        return ;
                    }

                    //  GridController
                    _gridController = new GridController(false);
                    _gridController.InitGrid(_mTab, true, _windowNo, null, null);

                    _gridController.RegisterIBusy(this);
                    //_gridController.Size = new Size(300, 100);
                    tblMain.Children.Add(_gridController);
                    //tblMain.SetColumnSpan(_gridController, 2);

                    _bs = _gridController.GetBindingSource();

                    _gridController.vTable.SelectionChanged += new SelectionChangedEventHandler(vTable_SelectionChanged);

                    //  Prepare Parameter
                    int tabNo = 0;

                    //	Alias

                    bool isHasAlies = _AcctSchema.IsHasAlias();
                    if (isHasAlies)
                    {
                        GridField alias = _mTab.GetField("Alias");
                        f_Alias = VControlFactory.GetControl(_mTab, alias, false);
                        AddLine(alias, f_Alias, false);
                    }	//	Alias

                    //	Combination
                    GridField combination = _mTab.GetField("Combination");
                    f_Combination = VControlFactory.GetControl(_mTab, combination, false);
                    AddLine(combination, f_Combination, false);

                    //tblParameter.RowCount++;
                    tblParaMeter.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
                    
                    _newRow = true;


                    /**
                     *	Create Fields in Element Order
                     */

                    for (int i = 0; i < elements.Length; i++)
                    {
                        MAcctSchemaElement ase = elements[i];
                        String type = ase.GetElementType();
                        bool isMandatory = ase.IsMandatory();
                        //
                        if (type.Equals(MAcctSchemaElement.ELEMENTTYPE_Organization))
                        {
                            GridField field = _mTab.GetField("AD_Org_ID");
                            f_AD_Org_ID = VControlFactory.GetControl(_mTab, field, false);
                            AddLine(field, f_AD_Org_ID, isMandatory);
                        }
                        else if (type.Equals(MAcctSchemaElement.ELEMENTTYPE_Account))
                        {
                            GridField field = _mTab.GetField("Account_ID");
                            f_Account_ID = VControlFactory.GetControl(_mTab, field, false);
                            //	((VLookup)f_Account_ID).setWidth(400);
                            AddLine(field, f_Account_ID, isMandatory);
                            f_Account_ID.VetoableChangeListener += new EventHandler(f_Account_ID_VetoableChangeListener);
                        }
                        else if (type.Equals(MAcctSchemaElement.ELEMENTTYPE_SubAccount))
                        {
                            GridField field = _mTab.GetField("C_SubAcct_ID");
                            f_SubAcct_ID = VControlFactory.GetControl(_mTab, field, false);
                            //	((VLookup)f_SubAcct_ID).setWidth(400);
                            AddLine(field, f_SubAcct_ID, isMandatory);
                        }
                        else if (type.Equals(MAcctSchemaElement.ELEMENTTYPE_Product))
                        {
                            GridField field = _mTab.GetField("M_Product_ID");
                            f_M_Product_ID = VControlFactory.GetControl(_mTab, field, false);
                            AddLine(field, f_M_Product_ID, isMandatory);
                        }
                        else if (type.Equals(MAcctSchemaElement.ELEMENTTYPE_BPartner))
                        {
                            GridField field = _mTab.GetField("C_BPartner_ID");
                            f_C_BPartner_ID = VControlFactory.GetControl(_mTab, field, false);
                            AddLine(field, f_C_BPartner_ID, isMandatory);
                        }
                        else if (type.Equals(MAcctSchemaElement.ELEMENTTYPE_Campaign))
                        {
                            GridField field = _mTab.GetField("C_Campaign_ID");
                            f_C_Campaign_ID = VControlFactory.GetControl(_mTab, field, false);
                            AddLine(field, f_C_Campaign_ID, isMandatory);
                        }
                        else if (type.Equals(MAcctSchemaElement.ELEMENTTYPE_LocationFrom))
                        {
                            GridField field = _mTab.GetField("C_LocFrom_ID");
                            f_C_LocFrom_ID = VControlFactory.GetControl(_mTab, field, false);
                            AddLine(field, f_C_LocFrom_ID, isMandatory);
                        }
                        else if (type.Equals(MAcctSchemaElement.ELEMENTTYPE_LocationTo))
                        {
                            GridField field = _mTab.GetField("C_LocTo_ID");
                            f_C_LocTo_ID = VControlFactory.GetControl(_mTab, field, false);
                            AddLine(field, f_C_LocTo_ID, isMandatory);
                        }
                        else if (type.Equals(MAcctSchemaElement.ELEMENTTYPE_Project))
                        {
                            GridField field = _mTab.GetField("C_Project_ID");
                            f_C_Project_ID = VControlFactory.GetControl(_mTab, field, false);
                            AddLine(field, f_C_Project_ID, isMandatory);
                        }
                        else if (type.Equals(MAcctSchemaElement.ELEMENTTYPE_SalesRegion))
                        {
                            GridField field = _mTab.GetField("C_SalesRegion_ID");
                            f_C_SalesRegion_ID = VControlFactory.GetControl(_mTab, field, false);
                            AddLine(field, f_C_SalesRegion_ID, isMandatory);
                        }
                        else if (type.Equals(MAcctSchemaElement.ELEMENTTYPE_OrgTrx))
                        {
                            GridField field = _mTab.GetField("AD_OrgTrx_ID");
                            f_AD_OrgTrx_ID = VControlFactory.GetControl(_mTab, field, false);
                            AddLine(field, f_AD_OrgTrx_ID, isMandatory);
                        }
                        else if (type.Equals(MAcctSchemaElement.ELEMENTTYPE_Activity))
                        {
                            GridField field = _mTab.GetField("C_Activity_ID");
                            f_C_Activity_ID = VControlFactory.GetControl(_mTab, field, false);
                            AddLine(field, f_C_Activity_ID, isMandatory);
                        }
                        //	User1
                        else if (type.Equals(MAcctSchemaElement.ELEMENTTYPE_UserList1))
                        {
                            GridField field = _mTab.GetField("User1_ID");
                            f_User1_ID = VControlFactory.GetControl(_mTab, field, false);
                            AddLine(field, f_User1_ID, isMandatory);
                        }
                        else if (type.Equals(MAcctSchemaElement.ELEMENTTYPE_UserList2))
                        {
                            GridField field = _mTab.GetField("User2_ID");
                            f_User2_ID = VControlFactory.GetControl(_mTab, field, false);
                            AddLine(field, f_User2_ID, isMandatory);
                        }
                    }

                    //	Add description
                    _newRow = true;

                    //tblParameter.RowCount++;
                    tblParaMeter.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });

                    //f_Description.AutoSize = false;
                    f_Description.Height = 21;
                    //f_Description.TextAlign = ContentAlignment.MiddleCenter;
                    f_Description.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;

                    //f_Description.FontStyle  =    .Font = new Font(f_Description.Font, FontStyle.Italic);

                   // f_Description.Anchor = AnchorStyles.None;
                    //tblParameter.Controls.Add(f_Description, 0, tblParameter.RowCount - 1);

                    tblParaMeter.Children.Add(f_Description);//, 0, tblParameter.RowCount - 1);

                    Grid.SetColumn(f_Description, 0);
                    Grid.SetRow(f_Description, tblParaMeter.RowDefinitions.Count - 1);
                    Grid.SetColumnSpan(f_Description, 5);

                    //tblParameter.SetColumnSpan(f_Description, 5);
                   // f_Description.Dock = DockStyle.Fill;
                    f_Description.Visible = false;

                    tblParaMeter.RowDefinitions.Add(new RowDefinition(){ Height=GridLength.Auto});//  .RowCount++;
                    //parameterPanel.add(f_Description, m_gbc);

                    //	Finish
                    _query = new Query();
                    _query.AddRestriction("C_AcctSchema_ID", Query.EQUAL, _C_AcctSchema_ID);
                    _query.AddRestriction("IsFullyQualified", Query.EQUAL, "Y");
                    if (_mAccount.C_ValidCombination_ID == 0)
                        _mTab.SetQuery(Query.GetEqualQuery("1", "2"));
                    else
                    {
                        Query query = new Query();
                        query.AddRestriction("C_AcctSchema_ID", Query.EQUAL, _C_AcctSchema_ID);
                        query.AddRestriction("C_ValidCombination_ID", Query.EQUAL, _mAccount.C_ValidCombination_ID);
                        _mTab.SetQuery(query);
                    }
                    //_mTab.Query(0);
                    _gridController.query(0, 0, false);
                  



                    //***//_bs.PositionChanged += new EventHandler(_bs_PositionChanged);

                    statusBar.SetStatusLine(_AcctSchema.ToString());
                    statusBar.SetStatusDB("?");

                    //	Initial value
                    //if (_mAccount.C_ValidCombination_ID != 0)
                    //_mTab.navigate(0);

                    log.Config("fini");
                   // return true;
                    SetBusy(false);

                };
            bgw.RunWorkerAsync();
            return true;
            //	Get AcctSchema Info
        }

        void vTable_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            VDataGrid grd = (VDataGrid)sender;
            if (grd.ItemsSource == null || grd.SelectedIndex < 0)
            {
                return;
            }
            currentRow = grd.SelectedItem as DataUtil.DataObject;
            tblParaMeter.DataContext = currentRow;

            String info = currentRow.GetFieldValue("DESCRIPTION").ToString();
            _comb = currentRow.GetFieldValue("COMBINATION").ToString();
            _desc = info;
            f_Description.Content = info;
            f_Description.Visible = !(info.Trim() == "");
            if (rowCount == -1)
            {
                rowCount = grd.ItemsSource.OfType<object>().Count();
                statusBar.SetStatusDB(rowCount.ToString());
            }
        }

        void f_Account_ID_VetoableChangeListener(object sender, EventArgs e)
        {
            //throw new NotImplementedException();
        }


        /// <summary>
        ///	Add Editor to parameterPanel alernative right/left depending on m_newRow.
        ///  Field Value changes update Editors
        /// </summary>
        /// <param name="field"></param>
        /// <param name="editor"></param>
        /// <param name="mandatory"></param>
        private void AddLine(GridField field, IControl editor, bool mandatory)
        {
            log.Fine("Field=" + field);
            VLabel label = VControlFactory.GetLabel(field);
            //label.AutoSize = true;
            label.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;

            //label.Anchor = AnchorStyles.Right;
            //label.setLabelFor((Component)editor);
            editor.SetReadOnly(false);
            editor.SetIsMandatory(mandatory);
            //  MField => VEditor
            
            //***/((Control)editor).DataBindings.Add("BindValue", _bs, editor.GetName(), true);


            editor.BindValue = editor.GetName().ToUpper();
            
            //*****field.addPropertyChangeListener(editor);

            //	label
            if (_newRow)
            {
                tblParaMeter.Children.Add(label);//, 0, tblParameter.RowCount - 1);
                Grid.SetColumn(label, 0);
                Grid.SetRow(label,tblParaMeter.RowDefinitions.Count - 1);
            }
            else
            {
                tblParaMeter.Children.Add(label);//, 0, tblParameter.RowCount - 1);
                Grid.SetColumn(label, 3);
                Grid.SetRow(label, tblParaMeter.RowDefinitions.Count - 1);
                //tblParameter.Controls.Add(label, 3, tblParameter.RowCount - 1);
            }

            //	Field
            if (_newRow)
            {
                //tblParameter.Controls.Add((Control)editor, 1, tblParameter.RowCount - 1);
                ((Control)editor).Margin = new Thickness(1, 2, 1, 2);
                tblParaMeter.Children.Add((Control)editor);//, 0, tblParameter.RowCount - 1);
                Grid.SetColumn((Control)editor, 1);
                Grid.SetRow((Control)editor, tblParaMeter.RowDefinitions.Count - 1);
            }
            else
            {
                //tblParameter.Controls.Add((Control)editor, 4, tblParameter.RowCount - 1);

                ((Control)editor).Margin = new Thickness(1,2,1,2);
                tblParaMeter.Children.Add((Control)editor);//, 0, tblParameter.RowCount - 1);

                Grid.SetColumn((Control)editor, 4);
                Grid.SetRow((Control)editor, tblParaMeter.RowDefinitions.Count - 1);
            }

            //((Control)editor).Dock = DockStyle.Fill;

            if (!_newRow)
            {
                tblParaMeter.RowDefinitions.Add(new RowDefinition(){ Height= GridLength.Auto});// .RowCount++;
            }
            _newRow = !_newRow;

        }


        #region Button Click

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            _changed = true;
            SaveSelection();

            this.DialogResult = true;
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            _changed = false;
            SaveSelection();
            this.DialogResult = false;
        }


        protected override void OnClosed(EventArgs e)
        {
            if (_gridController != null)
                _gridController.Dispose();
            _gridController = null;
            //  Model
            _mTab = null;
            if (_mWindow != null)
                _mWindow.Dispose();
            _mWindow = null;
            Envs.ClearWinContext(_windowNo);

            currentRow = null;
            _bs = null;

            base.OnClosed(e);
        }

       

        private void btnRefresh_Click(object sender, RoutedEventArgs e)
        {
            Action_Find(true);
        }

        /**
   *	Action Find.
   *	- create where clause
   *	- query database
   *  @param includeAliasCombination include alias combination
   */
        private void Action_Find(bool includeAliasCombination)
        {
            log.Info("");
            SetBusy(true);
            //this.Cursor = Cursors.Wait;
            //setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
            //	Create where Clause
            Query query = null;
            if (_query != null)
                query = _query.DeepCopy();
            else
                query = new Query();
            //	Alias
            if (includeAliasCombination && f_Alias != null && f_Alias.GetValue().ToString().Length > 0)
            {
                String value = f_Alias.GetValue().ToString().ToUpper();
                if (!value.EndsWith("%"))
                    value += "%";
                query.AddRestriction("UPPER(Alias)", Query.LIKE, value);
            }
            //	Combination (mandatory)
            if (includeAliasCombination && f_Combination.GetValue().ToString().Length > 0)
            {
                String value = f_Combination.GetValue().ToString().ToUpper();
                if (!value.EndsWith("%"))
                    value += "%";
                query.AddRestriction("UPPER(Combination)", Query.LIKE, value);
            }
            //	Org (mandatory)
            if (f_AD_Org_ID != null && !IsNull(f_AD_Org_ID.GetValue()))
                query.AddRestriction("AD_Org_ID", Query.EQUAL, f_AD_Org_ID.GetValue());
            //	Account (mandatory)
            if (f_Account_ID != null && !IsNull(f_Account_ID.GetValue()))
                query.AddRestriction("Account_ID", Query.EQUAL, f_Account_ID.GetValue());

            if (f_SubAcct_ID != null && !IsNull(f_SubAcct_ID.GetValue()))
                query.AddRestriction("C_SubAcct_ID", Query.EQUAL, f_SubAcct_ID.GetValue());

            //	Product
            if (f_M_Product_ID != null && !IsNull(f_M_Product_ID.GetValue()))
                query.AddRestriction("M_Product_ID", Query.EQUAL, f_M_Product_ID.GetValue());
            //	BPartner
            if (f_C_BPartner_ID != null && !IsNull(f_C_BPartner_ID.GetValue()))
                query.AddRestriction("C_BPartner_ID", Query.EQUAL, f_C_BPartner_ID.GetValue());
            //	Campaign
            if (f_C_Campaign_ID != null && !IsNull(f_C_Campaign_ID.GetValue()))
                query.AddRestriction("C_Campaign_ID", Query.EQUAL, f_C_Campaign_ID.GetValue());
            //	Loc From
            if (f_C_LocFrom_ID != null && !IsNull(f_C_LocFrom_ID.GetValue()))
                query.AddRestriction("C_LocFrom_ID", Query.EQUAL, f_C_LocFrom_ID.GetValue());
            //	Loc To
            if (f_C_LocTo_ID != null && !IsNull(f_C_LocTo_ID.GetValue()))
                query.AddRestriction("C_LocTo_ID", Query.EQUAL, f_C_LocTo_ID.GetValue());
            //	Project
            if (f_C_Project_ID != null && !IsNull(f_C_Project_ID.GetValue()))
                query.AddRestriction("C_Project_ID", Query.EQUAL, f_C_Project_ID.GetValue());
            //	SRegion
            if (f_C_SalesRegion_ID != null && !IsNull(f_C_SalesRegion_ID.GetValue()))
                query.AddRestriction("C_SalesRegion_ID", Query.EQUAL, f_C_SalesRegion_ID.GetValue());
            //	Org Trx
            if (f_AD_OrgTrx_ID != null && !IsNull(f_AD_OrgTrx_ID.GetValue()))
                query.AddRestriction("AD_OrgTrx_ID", Query.EQUAL, f_AD_OrgTrx_ID.GetValue());
            //	Activity
            if (f_C_Activity_ID != null && !IsNull(f_C_Activity_ID.GetValue()))
                query.AddRestriction("C_Activity_ID", Query.EQUAL, f_C_Activity_ID.GetValue());
            //	User 1
            if (f_User1_ID != null && !IsNull(f_User1_ID.GetValue()))
                query.AddRestriction("User1_ID", Query.EQUAL, f_User1_ID.GetValue());
            //	User 2
            if (f_User2_ID != null && !IsNull(f_User2_ID.GetValue()))
                query.AddRestriction("User2_ID", Query.EQUAL, f_User2_ID.GetValue());

            //	Query
            _mTab.SetQuery(query);
            //_bs.PositionChanged -= new EventHandler(_bs_PositionChanged);
            //_bs = null;
            _gridController.query(0, 0, false);
            //_bs = _gridController.GetDataSource();
            //_bs.PositionChanged += new EventHandler(_bs_PositionChanged);
            //_mTab.Query(0);
           // statusBar.SetStatusDB(_bs.Count.ToString());
           // this.Cursor = Cursors.Default;

        }

        private void btnIgnore_Click(object sender, RoutedEventArgs e)
        {
            Action_Ignore();
        }

        /**
        *	Ignore
        */
        private void Action_Ignore()
        {
            if (f_Alias != null)
                f_Alias.SetValue("");
            f_Combination.SetValue("");
            f_Description.Content = "";
            f_Description.Visible = false;
            //
            //	Org (mandatory)
            f_AD_Org_ID.SetValue(null);
            //	Account (mandatory)
            f_Account_ID.SetValue(null);
            if (f_SubAcct_ID != null)
                f_SubAcct_ID.SetValue(null);

            //	Product
            if (f_M_Product_ID != null)
                f_M_Product_ID.SetValue(null);
            //	BPartner
            if (f_C_BPartner_ID != null)
                f_C_BPartner_ID.SetValue(null);
            //	Campaign
            if (f_C_Campaign_ID != null)
                f_C_Campaign_ID.SetValue(null);
            //	Loc From
            if (f_C_LocFrom_ID != null)
                f_C_LocFrom_ID.SetValue(null);
            //	Loc To
            if (f_C_LocTo_ID != null)
                f_C_LocTo_ID.SetValue(null);
            //	Project
            if (f_C_Project_ID != null)
                f_C_Project_ID.SetValue(null);
            //	SRegion
            if (f_C_SalesRegion_ID != null)
                f_C_SalesRegion_ID.SetValue(null);
            //	Org Trx
            if (f_AD_OrgTrx_ID != null)
                f_AD_OrgTrx_ID.SetValue(null);
            //	Activity
            if (f_C_Activity_ID != null)
                f_C_Activity_ID.SetValue(null);
            //	User 1
            if (f_User1_ID != null)
                f_User1_ID.SetValue(null);
            //	User 2
            if (f_User2_ID != null)
                f_User2_ID.SetValue(null);
        }
        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            Action_Save();
        }

        /**
        *	Create/Save Account
        */
        private void Action_Save()
        {
            log.Info("");

            SetBusy(true);

            /**
             *	Check completeness (mandatory fields) ... and for duplicates
             */
            StringBuilder sb = new StringBuilder();
            StringBuilder sql = new StringBuilder("SELECT C_ValidCombination_ID, Alias FROM C_ValidCombination WHERE ");
            Object value = null;
            if (_AcctSchema.IsHasAlias())
            {
                value = f_Alias.GetValue();
                if (value == null)
                    sb.Append(Msg.Translate(Envs.GetCtx(), "Alias")).Append(", ");
            }
            MAcctSchemaElement[] elements = _AcctSchema.GetAcctSchemaElements();
            for (int i = 0; i < elements.Length; i++)
            {
                MAcctSchemaElement ase = elements[i];
                String type = ase.GetElementType();
                //
                if (type.Equals(MAcctSchemaElement.ELEMENTTYPE_Organization))
                {
                    value = f_AD_Org_ID.GetValue();
                    sql.Append("AD_Org_ID");
                    if (IsNull(value))
                        sql.Append(" IS NULL AND ");
                    else
                        sql.Append("=").Append(value).Append(" AND ");
                }
                else if (type.Equals(MAcctSchemaElement.ELEMENTTYPE_Account))
                {
                    value = f_Account_ID.GetValue();
                    sql.Append("Account_ID");
                    if (IsNull(value))
                        sql.Append(" IS NULL AND ");
                    else
                        sql.Append("=").Append(value).Append(" AND ");
                }
                else if (type.Equals(MAcctSchemaElement.ELEMENTTYPE_SubAccount))
                {
                    value = f_SubAcct_ID.GetValue();
                    sql.Append("C_SubAcct_ID");
                    if (IsNull(value))
                        sql.Append(" IS NULL AND ");
                    else
                        sql.Append("=").Append(value).Append(" AND ");
                }
                else if (type.Equals(MAcctSchemaElement.ELEMENTTYPE_Product))
                {
                    value = f_M_Product_ID.GetValue();
                    sql.Append("M_Product_ID");
                    if (IsNull(value))
                        sql.Append(" IS NULL AND ");
                    else
                        sql.Append("=").Append(value).Append(" AND ");
                }
                else if (type.Equals(MAcctSchemaElement.ELEMENTTYPE_BPartner))
                {
                    value = f_C_BPartner_ID.GetValue();
                    sql.Append("C_BPartner_ID");
                    if (IsNull(value))
                        sql.Append(" IS NULL AND ");
                    else
                        sql.Append("=").Append(value).Append(" AND ");
                }
                else if (type.Equals(MAcctSchemaElement.ELEMENTTYPE_Campaign))
                {
                    value = f_C_Campaign_ID.GetValue();
                    sql.Append("C_Campaign_ID");
                    if (IsNull(value))
                        sql.Append(" IS NULL AND ");
                    else
                        sql.Append("=").Append(value).Append(" AND ");
                }
                else if (type.Equals(MAcctSchemaElement.ELEMENTTYPE_LocationFrom))
                {
                    value = f_C_LocFrom_ID.GetValue();
                    sql.Append("C_LocFrom_ID");
                    if (IsNull(value))
                        sql.Append(" IS NULL AND ");
                    else
                        sql.Append("=").Append(value).Append(" AND ");
                }
                else if (type.Equals(MAcctSchemaElement.ELEMENTTYPE_LocationTo))
                {
                    value = f_C_LocTo_ID.GetValue();
                    sql.Append("C_LocTo_ID");
                    if (IsNull(value))
                        sql.Append(" IS NULL AND ");
                    else
                        sql.Append("=").Append(value).Append(" AND ");
                }
                else if (type.Equals(MAcctSchemaElement.ELEMENTTYPE_Project))
                {
                    value = f_C_Project_ID.GetValue();
                    sql.Append("C_Project_ID");
                    if (IsNull(value))
                        sql.Append(" IS NULL AND ");
                    else
                        sql.Append("=").Append(value).Append(" AND ");
                }
                else if (type.Equals(MAcctSchemaElement.ELEMENTTYPE_SalesRegion))
                {
                    value = f_C_SalesRegion_ID.GetValue();
                    sql.Append("C_SalesRegion_ID");
                    if (IsNull(value))
                        sql.Append(" IS NULL AND ");
                    else
                        sql.Append("=").Append(value).Append(" AND ");
                }
                else if (type.Equals(MAcctSchemaElement.ELEMENTTYPE_OrgTrx))
                {
                    value = f_AD_OrgTrx_ID.GetValue();
                    sql.Append("AD_OrgTrx_ID");
                    if (IsNull(value))
                        sql.Append(" IS NULL AND ");
                    else
                        sql.Append("=").Append(value).Append(" AND ");
                }
                else if (type.Equals(MAcctSchemaElement.ELEMENTTYPE_Activity))
                {
                    value = f_C_Activity_ID.GetValue();
                    sql.Append("C_Activity_ID");
                    if (IsNull(value))
                        sql.Append(" IS NULL AND ");
                    else
                        sql.Append("=").Append(value).Append(" AND ");
                }
                else if (type.Equals(MAcctSchemaElement.ELEMENTTYPE_UserList1))
                {
                    value = f_User1_ID.GetValue();
                    sql.Append("User1_ID");
                    if (IsNull(value))
                        sql.Append(" IS NULL AND ");
                    else
                        sql.Append("=").Append(value).Append(" AND ");
                }
                else if (type.Equals(MAcctSchemaElement.ELEMENTTYPE_UserList2))
                {
                    value = f_User2_ID.GetValue();
                    sql.Append("User2_ID");
                    if (IsNull(value))
                        sql.Append(" IS NULL AND ");
                    else
                        sql.Append("=").Append(value).Append(" AND ");
                }
                //
                if (ase.IsMandatory() && (value == null || value == DBNull.Value))
                    sb.Append(ase.GetName()).Append(", ");
            }	//	Fields in Element Order

            if (sb.Length != 0)
            {
                ShowMessage.Error("FillMandatory", null, sb.ToString().Substring(0, sb.Length - 2));
                //ADialog.error(m_WindowNo, this, "FillMandatory", sb.substring(0, sb.length() - 2));
                SetBusy(false);
                return;
            }
            if (f_AD_Org_ID == null || IsNull(f_AD_Org_ID.GetValue()))
            {
                ShowMessage.Error("FillMandatory", null, Msg.GetElement(Envs.GetCtx(), "AD_Org_ID"));
                //ADialog.error(m_WindowNo, this, "FillMandatory", Msg.getElement(Env.getCtx(), "AD_Org_ID"));
                SetBusy(false);
                return;
            }
            if (f_Account_ID == null || IsNull(f_Account_ID.GetValue()))
            {
                ShowMessage.Error("FillMandatory", null, Msg.GetElement(Envs.GetCtx(), "Account_ID"));
                //ADialog.error(m_WindowNo, this, "FillMandatory", Msg.getElement(Env.getCtx(), "Account_ID"));
                SetBusy(false);
                return;
            }


            /**
             *	Check if already exists
             */
            sql.Append("AD_Client_ID=" + _AD_Client_ID + " AND C_AcctSchema_ID=" + _AcctSchema.GetC_AcctSchema_ID());
            log.Fine("Check = " + sql.ToString());
            int IDvalue = 0;
            String Alias = null;
            IDataReader dr = null;


            //Check Alies Value
            string alies = f_Alias.GetValue().ToString();
            BackgroundWorker bgw = new BackgroundWorker();

            string f_alies = f_Alias.GetValue().ToString();

            bgw.DoWork += (ds, dc) =>
                {
                    try
                    {
                        dr = DB.ExecuteReader(sql.ToString(), null);
                        if (dr.Read())
                        {
                            IDvalue = Util.GetValueOfInt(dr[0]);
                            Alias = Util.GetValueOfString(dr[1]);
                        }
                        dr.Close();
                        dr = null;
                    }
                    catch (System.ArgumentOutOfRangeException e)
                    {
                        log.Log(Level.SEVERE, sql.ToString(), e);
                        IDvalue = 0;
                        if (dr != null)
                        {
                            dr.Close();
                            dr = null;
                        }
                    }
                    catch (System.Exception e)
                    {
                        log.Log(Level.SEVERE, sql.ToString(), e);
                        IDvalue = 0;
                        if (dr != null)
                        {
                            dr.Close();
                            dr = null;
                        }
                    }
                    finally
                    {
                        if (dr != null)
                        {
                            dr.Close();
                        }
                    }
                    log.Fine("ID=" + IDvalue + ", Alias=" + Alias);
                    if (Alias == null)
                        Alias = "";
                    //	We have an account like this already - check alias
                    if (IDvalue != 0 && _AcctSchema.IsHasAlias()
                       && f_alies.Equals(Alias))
                    {
                        sql = new StringBuilder("UPDATE C_ValidCombination SET Alias=");
                        if (f_alies.ToString().Length == 0)
                            sql.Append("NULL");
                        else
                            sql.Append("'").Append(f_alies).Append("'");
                        sql.Append(" WHERE C_ValidCombination_ID=").Append(IDvalue);
                        int i = 0;
                        try
                        {
                            i = DB.ExecuteQuery(sql.ToString());
                        }
                        catch (Exception e)
                        {
                            log.Log(Level.SEVERE, sql.ToString(), e);
                        }
                        if (i == 0)
                        {
                            //ShowMessage.Error("AccountNotUpdated", null);
                        }
                    }
                };

            bgw.RunWorkerCompleted += (cs, ce) =>
                {
                    if (IDvalue != 0)
                    {
                        LoadInfo(IDvalue, _AcctSchema.GetC_AcctSchema_ID());
                        // Action_Find(false);
                        return;
                    }

                    //	load and display

                    log.Config("New");
                    Alias = null;
                    if (f_Alias != null)
                        Alias = f_Alias.GetValue().ToString();
                    int C_SubAcct_ID = 0;
                    if (f_SubAcct_ID != null && (f_SubAcct_ID.GetValue() != null || f_SubAcct_ID.GetValue() != DBNull.Value))
                        C_SubAcct_ID = (int)f_SubAcct_ID.GetValue();
                    int M_Product_ID = 0;
                    if (f_M_Product_ID != null && !IsNull(f_M_Product_ID.GetValue()))
                        M_Product_ID = (int)f_M_Product_ID.GetValue();
                    int C_BPartner_ID = 0;
                    if (f_C_BPartner_ID != null && !IsNull(f_C_BPartner_ID.GetValue()))
                        C_BPartner_ID = (int)f_C_BPartner_ID.GetValue();
                    int AD_OrgTrx_ID = 0;
                    if (f_AD_OrgTrx_ID != null && !IsNull(f_AD_OrgTrx_ID.GetValue()))
                        AD_OrgTrx_ID = (int)f_AD_OrgTrx_ID.GetValue();
                    int C_LocFrom_ID = 0;
                    if (f_C_LocFrom_ID != null && !IsNull(f_C_LocFrom_ID.GetValue()))
                        C_LocFrom_ID = (int)f_C_LocFrom_ID.GetValue();
                    int C_LocTo_ID = 0;
                    if (f_C_LocTo_ID != null && !IsNull(f_C_LocTo_ID.GetValue()))
                        C_LocTo_ID = (int)f_C_LocTo_ID.GetValue();
                    int C_SRegion_ID = 0;
                    if (f_C_SalesRegion_ID != null && !IsNull(f_C_SalesRegion_ID.GetValue()))
                        C_SRegion_ID = (int)f_C_SalesRegion_ID.GetValue();
                    int C_Project_ID = 0;
                    if (f_C_Project_ID != null && !IsNull(f_C_Project_ID.GetValue()))
                        C_Project_ID = (int)f_C_Project_ID.GetValue();
                    int C_Campaign_ID = 0;
                    if (f_C_Campaign_ID != null && !IsNull(f_C_Campaign_ID.GetValue()))
                        C_Campaign_ID = (int)f_C_Campaign_ID.GetValue();
                    int C_Activity_ID = 0;
                    if (f_C_Activity_ID != null && !IsNull(f_C_Activity_ID.GetValue()))
                        C_Activity_ID = (int)f_C_Activity_ID.GetValue();
                    int User1_ID = 0;
                    if (f_User1_ID != null && !IsNull(f_User1_ID.GetValue()))
                        User1_ID = (int)f_User1_ID.GetValue();
                    int User2_ID = 0;
                    if (f_User2_ID != null && !IsNull(f_User2_ID.GetValue()))
                        User2_ID = (int)f_User2_ID.GetValue();

                    int AD_Org_ID = (int)f_AD_Org_ID.GetValue();
                    int AD_Account_ID = (int)f_Account_ID.GetValue();

                    ThreadPool.QueueUserWorkItem(delegate
                    {

                        MAccount acct = MAccount.Get(Envs.GetContext(), _AD_Client_ID,
                            AD_Org_ID,
                            _AcctSchema.GetC_AcctSchema_ID(),
                            AD_Account_ID, C_SubAcct_ID,
                            M_Product_ID, C_BPartner_ID, AD_OrgTrx_ID,
                            C_LocFrom_ID, C_LocTo_ID, C_SRegion_ID,
                            C_Project_ID, C_Campaign_ID, C_Activity_ID,
                            User1_ID, User2_ID, 0, 0);

                        if (acct != null && acct.Get_ID() == 0)
                            acct.Save();

                        //  Show Info
                        if (acct == null || acct.Get_ID() == 0)
                        {
                            Dispatcher.BeginInvoke(() => LoadInfo(0, 0));
                        }
                        else
                        {
                            //	Update Account with optional Alias
                            bool found = false;
                            if (Alias != null && Alias.Length > 0)
                            {

                                String sql1 = "SELECT COUNT(*) FROM C_ValidCombination WHERE Alias='" + Alias + "'";
                                int ii = DB.GetSQLValue(null, sql1);



                                if (ii != 0)
                                {
                                    found = true;
                                    // ShowMessage.Error("DuplicateAlias", null);
                                    // return;
                                }
                                else
                                {
                                    acct.SetAlias(Alias);
                                    acct.Save();
                                }
                            }

                            Dispatcher.BeginInvoke(delegate
                            {
                                if (found)
                                {
                                    ShowMessage.Error("DuplicateAlias", null);
                                    SetBusy(false);
                                    return;
                                }
                                else
                                {
                                    LoadInfo(acct.Get_ID(), _AcctSchema.GetC_AcctSchema_ID());
                                }
                            });
                        }
                        //Action_Find(false);
                    });
                };
            bgw.RunWorkerAsync();
        }

        #endregion

        private bool IsNull(object value)
        {
            if (value == null || value.Equals(DBNull.Value))
            {
                return true;
            }
            return false;
        }
        /// <summary>
        /// Get selected account
        /// </summary>
        /// <returns></returns>
        public int? GetValue()
        {
            log.Config("C_ValidCombination_ID=" + _C_ValidCombination_ID + ", Changed=" + _changed);
            if (!_changed || _C_ValidCombination_ID == 0)
                return null;
            return _C_ValidCombination_ID;
        }


        private string _desc = "", _comb = "";

        public String  GetCombination()
        {
            return _comb;
        }

        public String GetDescription()
        {
            return _desc;
        }


        private void SaveSelection()
        {
            if (_changed && _gridController != null)
            {
                //int row = m_gridController.getTable().getSelectedRow();
                if (currentRow != null)
                {
                    object id =  currentRow.GetFieldValue("C_ValidCombination_ID".ToUpper());
                    if (id != DBNull.Value && id != null)
                    {
                        _C_ValidCombination_ID = Convert.ToInt32(id);
                    }
                }
                log.Config("(" + _bs + ") - " + _C_ValidCombination_ID);
            }
        }	//

        /**
    *	Load Information
    *  @param C_ValidCombination_ID valid combination
    *  @param C_AcctSchema_ID acct schema
    */
        private void LoadInfo(int C_ValidCombination_ID, int C_AcctSchema_ID)
        {

            log.Fine("C_ValidCombination_ID=" + C_ValidCombination_ID);
            BackgroundWorker bgw = new BackgroundWorker();

            String sql = "SELECT * FROM C_ValidCombination WHERE C_ValidCombination_ID=" + C_ValidCombination_ID + " AND C_AcctSchema_ID=" + C_AcctSchema_ID;
            IDataReader dr = null;
            bgw.DoWork += (ds, de) =>
                {
                    dr = DB.ExecuteReader(sql);
                };
            bgw.RunWorkerCompleted += (cs, ce) =>
                {
                    try
                    {

                        if (dr.Read())
                        {
                            if (f_Alias != null)
                                f_Alias.SetValue(dr["Alias"].ToString());
                            f_Combination.SetValue(dr["Combination"].ToString());
                            //
                            LoadInfoOf(dr, f_AD_Org_ID, "AD_Org_ID");
                            LoadInfoOf(dr, f_Account_ID, "Account_ID");
                            LoadInfoOf(dr, f_SubAcct_ID, "C_SubAcct_ID");
                            //
                            LoadInfoOf(dr, f_M_Product_ID, "M_Product_ID");
                            LoadInfoOf(dr, f_C_BPartner_ID, "C_BPartner_ID");
                            LoadInfoOf(dr, f_C_Campaign_ID, "C_Campaign_ID");
                            LoadInfoOf(dr, f_C_LocFrom_ID, "C_LocFrom_ID");
                            LoadInfoOf(dr, f_C_LocTo_ID, "C_LocTo_ID");
                            LoadInfoOf(dr, f_C_Project_ID, "C_Project_ID");
                            LoadInfoOf(dr, f_C_SalesRegion_ID, "C_SalesRegion_ID");
                            LoadInfoOf(dr, f_AD_OrgTrx_ID, "AD_OrgTrx_ID");
                            LoadInfoOf(dr, f_C_Activity_ID, "C_Activity_ID");
                            LoadInfoOf(dr, f_User1_ID, "User1_ID");
                            LoadInfoOf(dr, f_User2_ID, "User2_ID");
                            //
                            f_Description.Content = dr["Description"].ToString();
                        }
                        dr.Close();
                        dr = null;
                    }
                    catch (SystemException e)
                    {
                        log.Log(Level.SEVERE, sql, e);
                        if (dr != null)
                        {
                            dr.Close();
                            dr = null;
                        }
                    }
                    catch (Exception e)
                    {
                        log.Log(Level.SEVERE, sql, e);
                        if (dr != null)
                        {
                            dr.Close();
                            dr = null;
                        }
                    }

                    Action_Find(false);
                };
            bgw.RunWorkerAsync();
        }

        /// <summary>
        ///	Set Value of Editor
        /// </summary>
        /// <param name="dr"></param>
        /// <param name="editor"></param>
        /// <param name="name"></param>
        private void LoadInfoOf(IDataReader dr, IControl editor, String name)
        {
            try
            {
                if (editor == null)
                    return;
                object value = dr[name];
                if (value == DBNull.Value)
                    editor.SetValue(null);
                else if (editor is VTextBoxButton)
                {
                    ((VTextBoxButton)editor).SetGetValue(Convert.ToInt32(value), false);
                }
                else if (editor is VComboBox)
                {
                    if (value is string)
                    {
                        editor.SetValue(dr[name].ToString());
                    }
                    else
                    {
                        editor.SetValue(Convert.ToInt32(dr[name]));
                    }
                }
                else
                {
                    editor.SetValue(value);
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
    }
}

